/*
 * Copyright (c) 2016. Darryl Burke - Burke Consulting
 *
 * This file is part of Android Malware Example.
 *
 *     Android Malware Example is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Android Malware Example is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Android Malware Example.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package com.burke_consulting.malwareexample;
/*
 * Developer : Darryl Burke (darrylb@burke-consulting.net)
 * Date : 01/08/2012
 * All code (c)2012 Burke Consulting. all rights reserved
 */

import android.util.Log;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlSerializer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


public class XmlUtils {

    public Document LoadXMLDoc(String doc) {

        //	Log.i("NSCModule", "Loading Xml:" + doc);

        Document tmpdoc = null;
        InputStream _objdoc = null;

        try {

            _objdoc = new FileInputStream(doc);

            DocumentBuilderFactory doc_build_fact = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder doc_builder = doc_build_fact
                    .newDocumentBuilder();

            //Log.i("NSCModule", "PreParse Xml:");

            tmpdoc = doc_builder.parse(_objdoc);

            //	Log.i("NSCModule", "PostParse Xml:");

        } catch (FileNotFoundException e) {
            Log.i("LMSModule", "XML Load Exception:" + e.toString());

            // TODO Auto-generated catch block
            // return tmpdoc;
        } catch (ParserConfigurationException e) {
            Log.i("LMSModule", "XML Load Exception:" + e.toString());

            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (SAXException e) {
            Log.i("LMSModule", "XML Load Exception:" + e.toString());

            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (IOException e) {
            Log.i("LMSModule", "XML Load Exception:" + e.toString());

            // TODO Auto-generated catch block
            // e.printStackTrace();
        }
        return tmpdoc;

    }


    public String getAttr(Element node, String attr) {
        return getAttr((Node) node, attr);
    }

    public String getAttr(Node node, String attr) {
        NamedNodeMap Attrs = node.getAttributes();

        Node _Desc = (Node) Attrs.getNamedItem(attr);
        // Log.i("FF:","Attr["+_Desc.getNodeName()+"]"+_Desc.getNodeValue());
        return (_Desc.getNodeValue());
    }

    public String getNodeAttr(NamedNodeMap attrnodes, String attr) {
        Node _Desc = (Node) attrnodes.getNamedItem(attr);
        String _d = _Desc.getNodeValue();
        return (_d);
    }

    public static Element getChildByName(Node e, String name) {
        return getChildByName((Element) e, name);
    }

    public static Element getChildByName(Element e, String name) {
        NodeList l = e.getChildNodes();
        if (l == null || l.getLength() == 0)
            return null; // not found

        for (int i = 0; i < l.getLength(); i++) {
            Node n = l.item(i);
            if ((n instanceof Element) && n.getNodeName().equals(name))
                return (Element) n;
        }
        return null; // not found
    }

    public static String getInnerNodeText(Node e) {

        return (getInnerText((Element) e));
    }

    public static String getInnerText(Node _a) {
        NodeList l = _a.getChildNodes();
        if (l == null || l.getLength() == 0)
            return ""; // / empty

        int idx = 0;
        while (idx < l.getLength()) {
            if (l.item(idx).getNodeType() == Node.TEXT_NODE)
                return l.item(idx).getNodeValue();
            idx++;
        }
        return ""; // no #text node found, so return empty string
    }

    public static void setInnerTextNode(Node e, String val) {
        NodeList l = e.getChildNodes();
        if (l != null && l.getLength() > 0) {
            int idx = 0;
            while (idx < l.getLength()) {
                Node n = l.item(idx);
                if (n.getNodeType() == Node.TEXT_NODE) {
                    // n.setNodeValue(val); // this isn't changing value!!
                    Node text = e.getOwnerDocument().createTextNode(val);
                    e.replaceChild(text, n);
                    return;
                }
                idx++;
            }
        }
        // no #text Node, so create one
        Node text = e.getOwnerDocument().createTextNode(val);
        e.appendChild(text);
    }

    public static void setInnerText(Element e, String val) {
        NodeList l = e.getChildNodes();
        if (l != null && l.getLength() > 0) {
            int idx = 0;
            while (idx < l.getLength()) {
                Node n = l.item(idx);
                if (n.getNodeType() == Node.TEXT_NODE) {
                    // n.setNodeValue(val); // this isn't changing value!!
                    Node text = e.getOwnerDocument().createTextNode(val);
                    e.replaceChild(text, n);
                    return;
                }
                idx++;
            }
        }
        // no #text Node, so create one
        Node text = e.getOwnerDocument().createTextNode(val);
        e.appendChild(text);
    }

    public static void writeElementTo(Element e, XmlSerializer s)
            throws IOException {
        s.startTag("", e.getNodeName());
        if (e.hasAttributes()) {
            NamedNodeMap m = e.getAttributes();
            for (int i = 0; i < m.getLength(); i++) {
                Node n = m.item(i);
                s.attribute("", n.getNodeName(), n.getNodeValue());
            }
        }
        if (e.hasChildNodes()) {
            NodeList kids = e.getChildNodes();
            for (int i = 0; i < kids.getLength(); i++) {
                Node n = kids.item(i);
                if (n.getNodeType() == Node.ELEMENT_NODE)
                    writeElementTo((Element) n, s); // recursively write child
                    // element
                else if (n.getNodeType() == Node.TEXT_NODE) {
                    s.text(n.getNodeValue());
                }
            }
        }

        s.endTag("", e.getNodeName());
    }

}

